import * as bajaService from '@/services/bajaService';
import { CORE_JAR_PREFIX } from '@/utils/constants';
import memoryUtils from '@/utils/memoryUtils';

export default {
  namespace: 'subSystem',
  state: {
    $handle: '',
    $typeSpec: CORE_JAR_PREFIX + ':CommonSubSystem',
    title: '',
    nIcon: '',
    subSystemType: 'page',
    pagePath: '',
    url: '',
    navOrd: '',
    subModules: [],
  },
  reducers: {
    setData(state, { payload }) {
      return { ...state, ...payload};
    },
    // setSelectedModuleIndex(state, {payload: {selectedModuleIndex}}) {
    //   return { ...state, selectedModuleIndex};
    // }
  },
  effects: {
    *fetch({ payload: {subSystemOrd} }, { call, put }) {
      let $handle='', $typeSpec='', title='', nIcon='', subSystemType='page', pagePath='', url='', navOrd='', subModules=[];
      const subSystem = yield call(bajaService.Ord, subSystemOrd);
      if(subSystem) {
        $handle = subSystem.$handle;
        $typeSpec = subSystem.getType().$typeSpec;
        title = subSystem.getTitle();
        nIcon = subSystem.getNIcon();
        navOrd = subSystem.getNavOrd().toString();
        if(!$typeSpec.endsWith('SubSystemGroup')) {
          const { $ordinal } =  subSystem.getSubSystemType();
          subSystemType = memoryUtils.SUBSYSTEM_TYPE[$ordinal];
          pagePath = subSystem.getPagePath();
          url = subSystem.getUrl();
          const modulesRoot = yield call(bajaService.Ord, navOrd+'/modulesRoot');
          if(modulesRoot) {
            memoryUtils.MODULE_TYPE = {};
            subModules = yield call(bajaService.fetchNavChildren, modulesRoot);
            subModules = yield call(bajaService.fetchSubModules, subModules);
            if(!subModules) {
              subModules = []
            }
          }
        }
      }
      yield put({ type: 'setData', payload: {
          $handle,
          $typeSpec,
          title,
          nIcon,
          subSystemType,
          pagePath,
          url,
          navOrd,
          subModules
        }});
    },
    // *selectModule({ payload: {selectedModuleIndex} }, { put }) {
    //   yield put({ type: 'setSelectedModuleIndex', payload: {selectedModuleIndex}});
    // }
  },

  // subscriptions: {
  //   setup({ dispatch, history }) {
  //     return history.listen(({ pathname }) => {
  //       const url = pathname.split("/");
  //       console.log("url", url);
  //       if (pathname.startsWith("/subSystem")) {
  //         // dispatch({ type: 'fetch', payload: {ord:'station:|h:'+url[2]}});
  //       }
  //     });
  //   },
  // },
}
